package com.example.langchain4j.remote;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.langchain4j.common.Result;
import com.example.langchain4j.utils.HttpUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
 * 第三方API调用服务类
 */

public class ChaiLiangApi {

    private static final String API_URL = "http://118.123.164.20:9800/dcnlp_zflc/www_pro_chat";

    private static final String AUTH_TOKEN = "b6eee957-5e1d-4273-a34a-f3997e7b030b";

    /**
     * 调用第三方API获取回答
     *
     * @param conversationId 会话ID
     * @param user 用户标识
     * @param query 查询内容
     * @return API返回结果
     * @throws Exception 网络或解析异常
     */
    public static Result<String> getContent(String conversationId, String user, String query) throws Exception {
        Map<String, String> headers = new HashMap<>();
        headers.put("Auth", AUTH_TOKEN);

        HashMap<String, Object> params = new HashMap<>();
        params.put("conversation_id", conversationId);
        params.put("user", user);
        params.put("query", query);

        return HttpUtils.streamResponse(API_URL, params, headers, data -> {
            String chunk = new String(data, StandardCharsets.UTF_8);
            if (chunk.startsWith("data:")) {
                String jsonData = chunk.substring(5).trim();
                JSONObject jsonObject = JSONUtil.parseObj(jsonData);
                Object message = jsonObject.get("message");
                JSONObject entries = JSONUtil.parseObj(message);
                String role = (String) entries.get("role");
                if ("assistant".equals(role)) {
                    return (String) entries.get("content");
                }
            }
            return null;
        });
    }

    /**
     * 调用第三方API获取完整响应（包含思考过程）
     *
     * @param conversationId 会话ID
     * @param user 用户标识
     * @param query 查询内容
     * @return 包含回答和思考过程的结果
     * @throws Exception 网络或解析异常
     */
    public static void getThinkAndContent(String conversationId, String user, String query) throws Exception {
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "text/event-stream");
        headers.put("Auth", AUTH_TOKEN);

        HashMap<String, Object> params = new HashMap<>();
        params.put("conversation_id", conversationId);
        params.put("user", user);
        params.put("query", query);

        StringBuilder content = new StringBuilder();
        StringBuilder think = new StringBuilder();

        Result<String> result = HttpUtils.streamResponse(API_URL, params, headers, data -> {
            String eventData = new String(data, StandardCharsets.UTF_8);
            if (eventData.startsWith("data:")) {
                String jsonData = eventData.substring(5).trim();
                JSONObject jsonObject = JSONUtil.parseObj(jsonData);
                Object message = jsonObject.get("message");
                JSONObject entries = JSONUtil.parseObj(message);
                String role = (String) entries.get("role");

                if ("think".equals(role)) {
                    String thinkContent = (String) entries.get("content");
                    think.append(thinkContent);
                }

                if ("assistant".equals(role)) {
                    String contentStr = (String) entries.get("content");
                    content.append(contentStr);
                }
            }
            return eventData;
        });

    }
}
